package com.yanqu.road.server.cross3server.cmd.activity.entername;

import com.yanqu.road.entity.activity.entername.UserEnterName;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.cross3.activity.EnterNameProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.cross3server.manager.Cross3EnterNameMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.protocol.ChannelProtocol;
import com.yanqu.road.server.protocol.Cross3Protocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;

@Cmd(code = Cross3Protocol.C3_ENTER_NAME_LOGIN_SYNC, desc = "登录")
public class Cross3EnterNameLoginSyncCmd extends CrossCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {

        EnterNameProto.CrossEnterNameSyncMsg reqMsg = EnterNameProto.CrossEnterNameSyncMsg.parseFrom(packet.getBytes());

        EnterNameProto.EnterNameSyncMsg.Builder syncMsg = EnterNameProto.EnterNameSyncMsg.newBuilder();

        for (int activityId : reqMsg.getActivityIdList()) {
            UserEnterName userEnterName = Cross3EnterNameMgr.getUserEnterName(activityId, packet.getPlayerId());
            if(userEnterName != null){
                EnterNameProto.UserEnterNameMsg.Builder builder = EnterNameProto.UserEnterNameMsg.newBuilder();
                builder.setActivityId(userEnterName.getActivityId());
                int groupId = Cross3EnterNameMgr.getGroupId(activityId, userEnterName.getZoneId());
                if(groupId != 0){
                    builder.setGroupId(groupId);
                }else {
                    builder.setGroupId(userEnterName.getGroupId());
                }

                builder.setZoneId(userEnterName.getZoneId());
                builder.setUserId(userEnterName.getUserId());
                syncMsg.addName(builder);

            }
        }

        MessageHelper.sendPacket(serverId, packet.getPlayerId(), YanQuMessageUtils.buildMessage(Protocol.U_ENTER_NAME_SYNC, syncMsg));
        Cross3EnterNameMgr.getLogger().info("enter name C3_ENTER_NAME_LOGIN_SYNC req, {}", StringUtils.listToString(reqMsg.getActivityIdList(), ","));

        if(reqMsg.getRewardActivityIdCount() > 0){
            EnterNameProto.ChannelEnterNameSyncMsg.Builder channelReq = EnterNameProto.ChannelEnterNameSyncMsg.newBuilder();
            channelReq.addAllActivityId(reqMsg.getRewardActivityIdList());
            channelReq.setUserKey(reqMsg.getKey());
            MessageHelper.sendChannelServer(YanQuMessageUtils.buildMessage(ChannelProtocol.N_ENTER_NAME_LOGIN_SYNC, channelReq));
        }
    }

    @Override
    public void sendData() {

    }
}
